import type { SplitOptions } from "./models/split-option";
import { readLine } from "./modules/read-line";

let n = 0;
let lines: string[] = [];

onmessage = (ev: MessageEvent<{ buffer: ArrayBuffer; options: SplitOptions }>) => {
  const { buffer, options } = ev.data;

  n = 0;
  lines = [];

  for (const { line, index } of readLine(buffer, options.stepSize)) {
    n++;
    lines.push(line);

    if (n % options.cacheSize === 0) {
      postMessage({ lines, index });
      lines = [];
    }
  }

  if (n % options.cacheSize > 0) postMessage({ lines, index: buffer.byteLength });

  postMessage("EOF");
};
